package com.ipay.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.ipay.dao.*;
import com.ipay.entity.*;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.beust.jcommander.internal.Maps;
import com.ipay.common.Base64Coder;
import com.ipay.redis.JedisConnectionPool;
import com.ipay.service.MerchantInfoService;
import com.ipay.utils.Constant;
import com.ipay.utils.DateUtils;
import com.ipay.utils.HttpUtils;
import com.ipay.utils.PinYinUtils;
import com.ipay.utils.RandomStringUtils;
import com.ipay.utils.StringUtil;

@Transactional
@Service("merchantInfoService")
public class MerchantInfoServiceImpl implements MerchantInfoService {
	@Autowired
	private MerchantInfoDao merchantInfoDao;
	@Autowired
	private CashiersDao cashiersDao;
	@Autowired
	private UserWechatInfoDao userWechatDao;
	@Autowired
	private MessagePushDao messagePushDao;
	@Autowired
	private QRCodeDao codeDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private MerchantRelationDao merchantRelationDao;
	@Autowired
	private BankInfoDao bankInfoDao;
	@Autowired
    private JedisConnectionPool pool;
	
	private Producer<String, String> producer;

	@Override
	public MerchantInfoEntity queryObject(Long id) {
		MerchantInfoEntity info = merchantInfoDao.queryObject(id);
		if(info != null){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("merchantNo", info.getMerchantNo());
			map.put("payState", Constant.Status.ENABLE.getValue());
			BankInfoEntity bankInfo = bankInfoDao.queryInfoByParams(map);
			if(bankInfo != null){
				info.setBankName(bankInfo.getBankName());
				info.setBankCard(bankInfo.getBankCard());
				info.setBankUser(bankInfo.getBankUser());
			}
		}
		return info;
	}

	@Override
	public List<MerchantInfoEntity> queryList(Map<String, Object> map) {
		return merchantInfoDao.queryList(map);
	}

	@Override
	public int queryTotal(Map<String, Object> map) {
		return merchantInfoDao.queryTotal(map);
	}
	
	@Override
	public MerchantInfoEntity queryInfoByMobile(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return merchantInfoDao.queryInfoByMobile(map);
	}

	@Override
	public void save(MerchantInfoEntity merchantInfo) {
		String merchantNo = DefaultSequenceManager.get().next(BizSequenceType.MERCHANTNO);//商户号
		merchantInfo.setMerchantNo(merchantNo);
		merchantInfo.setPresentNub(1);
		merchantInfoDao.save(merchantInfo);//商户表插入数据
		Long parentMerchantId = merchantInfo.getParentMerchantId();//父级商户主键id
		if(parentMerchantId != null && parentMerchantId != 0){
			MerchantInfoEntity info = merchantInfoDao.queryObject(parentMerchantId);
			MerchantRelation merchantRelation = new MerchantRelation();
			merchantRelation.setMerchantId(merchantInfo.getMerchantId());
			merchantRelation.setParentMerchantId(parentMerchantId);
			merchantRelation.setMerchantNo(merchantNo);
			merchantRelation.setParentMerchantNo(info.getMerchantNo());//父级商户编号
			merchantRelationDao.save(merchantRelation);
		}
		BankInfoEntity bankInfo = new BankInfoEntity();
		bankInfo.setBankCard(merchantInfo.getBankCard());
		bankInfo.setBankName(merchantInfo.getBankName());
		bankInfo.setBankUser(merchantInfo.getBankUser());
		bankInfo.setMerchantNo(merchantNo);
		bankInfo.setUseDesc(merchantInfo.getBankName());
		bankInfo.setPayState(Constant.Status.ENABLE.getValue());//默认银行卡状态启用
		bankInfo.setMobile(merchantInfo.getMobilephone());
		bankInfoDao.save(bankInfo);
	}

	@Override
	public void update(MerchantInfoEntity merchantInfo) {
		merchantInfoDao.update(merchantInfo);
	}

	@Override
	public void delete(Long id) {
		merchantInfoDao.delete(id);
	}

	@Override
	public void deleteBatch(Long[] ids) {
		//根据商户号逻辑删除该商户数据
		merchantInfoDao.deleteBatch(ids);
		//根据商户号逻辑删除该商户所关联的收款员数据
		cashiersDao.deleteBatch(ids);
		//根据商户号查询手机号码 修改系统用户表 状态为禁用
		sysUserDao.updateStatus(ids);
		//根据商户号逻辑删除该商户所关联的银行信息
		bankInfoDao.deleteBatchByMerchantNo(ids);
		//根据商户号逻辑删除该商户所关联的二维码信息
		codeDao.deleteBatchByMerchantNo(ids);
	}

	public MerchantInfoEntity queryByParams(MerchantInfoEntity entity) {
		Map<String, Object> map = Maps.newHashMap();
		map.put("shortUrl", entity.getShortUrl());
		if(entity.getMerchantNo() != null){
			map.put("merchantNo", entity.getMerchantNo());
		}
		return merchantInfoDao.queryByParams(map);
	}

	public void initWechatMgr(MerchantInfoEntity entity) {
		UserWechatInfo user = new UserWechatInfo();
		user.setOpenid(entity.getOpenid());
		user.setNickname(entity.getUsername());
		user.setSubscribe(1);
		user.setSex("1");
		userWechatDao.addWechatUserInfo(user);
	}
	
	@Override
	public Map<String, String> merchantVerify(MerchantInfoEntity merchantInfo) {
		CashiersEntity cash = new CashiersEntity();
		cash.setName(merchantInfo.getUsername());
		cash.setMobilePhone(merchantInfo.getMobilephone());
		cash.setActivateState(Constant.ActivateState.NOT_ACTIVE.getValue());
		cash.setMerchantId(merchantInfo.getMerchantNo());
		cash.setAuthority(Constant.AUTHORITY_YES);
		cash.setRole(Constant.ROLE_SH);
		String inviteCode = RandomStringUtils.randomNumeric(6);//随机生成邀请码
		cash.setInviteCode(inviteCode);
		cashiersDao.save(cash);
		
		merchantInfo.setPayKey(Base64Coder.key(192));
		
		String userName = merchantInfo.getShopAbbreviation();//登录帐号
		userName = PinYinUtils.toFirstChar(userName);
		//根据用户名称查询系统用户表 如果存在该名称 则在名称后加编号标识 例：lisi001
		List<SysUserEntity> listUser = sysUserDao.queryListByUserName(userName);
		if(listUser.size() > 0){
			userName += "00"+ String.valueOf(listUser.size()) + "adm";
		}else{
			userName += "adm";
		}
		
		//给商户增加一个登录帐号并分配一个角色
		SysUserEntity user = new SysUserEntity();
		user.setUsername(userName);
		user.setPassword(new Sha256Hash("123456").toHex());
		user.setUserType(Constant.USER_TYPE_SH);//用户类型 1：后台用户  2：商户
		user.setMobile(merchantInfo.getMobilephone());
		user.setEmail(merchantInfo.getEmail());
		user.setStatus(1);
		user.setCreateTime(new Date());
		user.setMerchantNo(merchantInfo.getMerchantNo());
		user.setCreateUserId(1L);
		sysUserDao.save(user);
		
		SysUserRoleEntity userRole = new SysUserRoleEntity();
		//判断该商户是一级商户还是二级商户、分配不同角色
		MerchantRelation relation = merchantRelationDao.queryObject(merchantInfo.getMerchantId());
		if(relation != null){//如果子商户表数据不为空表示该商户是子商户
			userRole.setRoleId(Long.valueOf("2"));//默认角色id 2 为二级商户角色
		}else{
			userRole.setRoleId(Long.valueOf("1"));//默认角色id 1 为一级商户角色
		}
		userRole.setUserId(user.getUserId());
		sysUserRoleDao.add(userRole);
		
		Map<String, String> resMap = new HashMap<String,String>();
		if(merchantInfo.getOpenid() != null){
			//往消息推送表中插入一条数据
			MessagePushEntity msg = new MessagePushEntity();
			msg.setOpenid(merchantInfo.getOpenid());
			msg.setMobilePhone(merchantInfo.getMobilephone());
			msg.setTitle("入驻审核结果通知");
			StringBuffer sb = new StringBuffer();
			sb.append("您好，您已成功通过了商户申请");
			sb.append("\n");
			sb.append("您的微信登录商户激活码为："+inviteCode);
			sb.append("\n");
			sb.append("您的后台登录帐号为："+userName);
			sb.append("\n");
			sb.append("默认登录密码为：123456");
			msg.setContent(sb.toString());
			msg.setStatus(0);
			messagePushDao.save(msg);
			resMap.put("msgId", msg.getId().toString());
		}
		resMap.put("inviteCode", inviteCode);
		resMap.put("userName", userName);
		//生成二维码
		String filePath = "";
		
		String date = DateUtils.format(new Date(), "yyyyMMdd");
        String random = RandomStringUtils.randomNumeric(6);
        //String codeNo = DefaultSequenceManager.get().next(BizSequenceType.QRCODE);
        String codeNo = date + random;
		
		StringBuffer qrurl = new StringBuffer();
		//下载时访问地址
		qrurl.append("merchant/userAgent");//http://www.***.cn/wechat/merchant/userAgent
		qrurl.append("?merchantNo=" + merchantInfo.getMerchantNo());// 商户号
		//com.ipay.core.QRCode.printQRCodeByLogo(new FileOutputStream(filePath), qrurl.toString(),codeNo,merchantInfo.getMerchantNo());
		
		QRCodeEntity qRCode = new QRCodeEntity();
		qRCode.setCodeName("一级主码");        //收款码名称
		qRCode.setCodeNo(codeNo);       //收款码编号
		qRCode.setMerchantId(merchantInfo.getMerchantNo()); //商户编号
		//qRCode.setSaveUrl(filePath);     //保存路径
		qRCode.setUserId(String.valueOf(cash.getId()));
		qRCode.setUrl(qrurl.toString());         //访问路径
		qRCode.setDeleteStatus(String.valueOf(Constant.DELETE_STATUS_YES));	//删除状态  0：未删除1：已删除 
		qRCode.setCodeStatus(Constant.CODE_STATUS_XT);		//二维码状态  0、系统生成 1、手动添加
		
		//根据商户号查询bankinfo表 主键id 与 默认二维码绑定
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("merchantNo", merchantInfo.getMerchantNo());
		List<BankInfoEntity> bankList = bankInfoDao.queryList(map);
		if(bankList.size()>0){
			qRCode.setBankId(bankList.get(0).getId());//银行信息表主键id
		}else{
			qRCode.setBankId(Long.parseLong("0"));//默认值
		}
		codeDao.insertQrCode(qRCode);
		
		
		merchantInfo.setPayQRUrl(filePath);
		merchantInfo.setPayUrl(qrurl.toString());
		merchantInfoDao.update(merchantInfo);
		return resMap;
	}

	@Override
	public void kafkaProducer() {
		Properties props = new Properties();
        // 此处配置的是kafka的端口
        props.put("metadata.broker.list", Constant.BROKER_LIST);
        props.put("zk.connect", Constant.ZOOKEEPER_CONTENT);
        // 配置value的序列化类
        props.put("serializer.class", "kafka.serializer.StringEncoder");
        // 配置key的序列化类
        props.put("key.serializer.class", "kafka.serializer.StringEncoder");
        props.put("request.required.acks", "-1");
        producer = new Producer<String, String>(new ProducerConfig(props));
	}

	@Override
	public void produce(String data) {
        String key = "1";
        producer.send(new KeyedMessage<String, String>(Constant.KAFKA_TOPIC, key, data));
        System.out.println("生产者消息=============="+data+"==========");
	}

	public static void main(String[] args){
		try {
			/* String content = URLEncoder.encode(
	                    "#merchant#=" + "系统管理员" + " " + "&#shop#="
	                            + merchantInfo.getShopName() + "&#mobile#=" + merchantInfo.getMobilephone()
	                            + "&#hour#=" + 1 + "&#code#=" + inviteCode
	                            + "&#company#=道合聚盈", "utf-8");*/
			 
			 String content = URLEncoder.encode(
	                    "#code#=" + "456135" + "&#username#="+ "18210639073" + 
	                    "&#password#=123456" + "&#company#=道合聚盈", "utf-8");
	
	            String tpl_id = "49348";
	            String result = HttpUtils.getValidCode("18210639073", tpl_id, content);
	            System.out.println("发送短信验证码返回结果：" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<MerchantInfoEntity> querySelectByParam(Map<String, Object> map) {
		return merchantInfoDao.querySelectByParam(map);
	}

	@Override
	public File[] creatFile(MerchantInfoEntity info) {
		
		ArrayList<File> list = new ArrayList<File>();
		
    	if(!StringUtil.isBlank(info.getPositiveImg())){
    		File file = new File(pool.getUploadImgPath() + info.getPositiveImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getOppositeImg())){
    		File file = new File(pool.getUploadImgPath() + info.getOppositeImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getInnerImg())){
    		File file = new File(pool.getUploadImgPath() + info.getInnerImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getOuterImg())){
    		File file = new File(pool.getUploadImgPath() + info.getOuterImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getDoorHeadImg())){
    		File file = new File(pool.getUploadImgPath() + info.getDoorHeadImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getBusinessLicenseImg())){
    		File file = new File(pool.getUploadImgPath() + info.getBusinessLicenseImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getBankLicenseImg())){
    		File file = new File(pool.getUploadImgPath() + info.getBankLicenseImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getSettlementBookImg())){
    		File file = new File(pool.getUploadImgPath() + info.getSettlementBookImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getSettleUserPositiveImg())){
    		File file = new File(pool.getUploadImgPath() + info.getSettleUserPositiveImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getSettleUserOppositeImg())){
    		File file = new File(pool.getUploadImgPath() + info.getSettleUserOppositeImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getSettleBankPositiveImg())){
    		File file = new File(pool.getUploadImgPath() + info.getSettleBankPositiveImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getSettleBankOppositeImg())){
    		File file = new File(pool.getUploadImgPath() + info.getSettleBankOppositeImg());
    		list.add(file);
    	}
    	if(!StringUtil.isBlank(info.getSealCardImg())){
    		File file = new File(pool.getUploadImgPath() + info.getSealCardImg());
    		list.add(file);
    	}
    	File[] tarFile = new File[list.size()];
    	for (int i = 0; i < list.size(); i++) {
    		tarFile[i] = list.get(i);
		}
    	//System.out.println("文件数组-------------------"+tarFile);
		return tarFile;
	}
}
